using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using WODPL.Models;

namespace WODPL.GameComponents
{
    public class MapTile : DrawableGameComponent
    {
        private readonly Vector3 dimensions;
        private readonly GameCamera camera;
        private MouseState prevState;
        private readonly MapTileModel mapTileModel;
        public event Action MapTileClicked;
        private bool isHovered;

        public MapTile(Game game, GameCamera camera, Vector3 dimensions, MapTileModel mapTileModel)
            : base(game)
        {
            this.camera = camera;
            this.mapTileModel = mapTileModel;
            this.dimensions = dimensions;
        }

        public override void Draw(GameTime gameTime)
        {
            base.Draw(gameTime);

            mapTileModel.MapTileRenderModel.BasicEffect.Alpha = isHovered ? 0.5f : 1f;
            mapTileModel.MapTileRenderModel.Draw(camera.ProjectionMatrix, camera.ViewMatrix, WorldMatrix);
        }

        private Matrix WorldMatrix
        {
            get { return Matrix.CreateScale(dimensions)*OriginWorldMatrix; }
        }

        private Matrix OriginWorldMatrix
        {
            get { return Matrix.CreateTranslation(mapTileModel.Origin);}
        }

        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);
            var state = Mouse.GetState();

            var startPoint = GraphicsDevice.Viewport.Unproject(new Vector3(state.X, state.Y, 0),
                                                                   camera.ProjectionMatrix,
                                                                   camera.ViewMatrix, OriginWorldMatrix);
            var endPoint = GraphicsDevice.Viewport.Unproject(new Vector3(state.X, state.Y, 1),
                                                             camera.ProjectionMatrix,
                                                             camera.ViewMatrix, OriginWorldMatrix);
            var ray = new Ray(startPoint, endPoint - startPoint);
            isHovered = ray.Intersects(mapTileModel.InteractionBox) != null;

            if (prevState == null)
            {
                prevState = state;
                return;
            }
            if (prevState.LeftButton == ButtonState.Released && state.LeftButton == ButtonState.Pressed && isHovered)
            {
                if (MapTileClicked != null) MapTileClicked();
            }

            prevState = state;
        }
    }
}